package cn.z2huo.algorithm.query.data;

import cn.hutool.core.text.csv.CsvWriteConfig;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 *
 * @author z2huo
 */
class CsvTestDataGenerator {

    private static final String TEST_DATA_PATH = "algorithm/src/test/resources/csv/query/";

    /**
     * <p>十万条和一百万条测试数据文件需要生成，没有提交到 git
     */
//    private static final int TEST_DATA_SIZE = 1_000;
//    private static final int TEST_DATA_SIZE = 10_000;
//    private static final int TEST_DATA_SIZE = 100_000;
    private static final int TEST_DATA_SIZE = 1_000_000;

    private static final int ARRAY_MIN_LENGTH = 50;

    private static final int ARRAY_MAX_LENGTH = 100;

    private static final int MAX_VALUE = 10000;

    public static void main(String[] args) throws FileNotFoundException {
        File file = ResourceUtils.getFile(TEST_DATA_PATH + "test_data_" + TEST_DATA_SIZE + ".csv");

        CsvWriteConfig csvWriteConfig = CsvWriteConfig.defaultConfig();

        try (FileWriter fileWriter = new FileWriter(file);
             CsvWriter csvWriter = new CsvWriter(fileWriter, csvWriteConfig)) {

            for (int i = 0; i < TEST_DATA_SIZE; i++) {
                int[] array = generateNoRepeatSortedArray();
                int index = RandomUtil.randomInt(0, array.length);

                csvWriter.writeLine(StringUtils.join(array, ';'), String.valueOf(array[index]), String.valueOf(index));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>生成正序数组
     * <p>数组中可能会有重复的值
     */
    private static int[] generateSortedArray() {
        int arrayLength = RandomUtil.randomInt(ARRAY_MIN_LENGTH, ARRAY_MAX_LENGTH + 1);
        int[] array = new int[arrayLength];
        for (int i = 0; i < array.length; i++) {
            array[i] = RandomUtil.randomInt(0, MAX_VALUE);
        }
        Arrays.sort(array);
        return array;
    }

    /**
     * <p>生成正序数组
     * <p>数组中不会出现重复元素
     */
    private static int[] generateNoRepeatSortedArray() {
        int arrayLength = RandomUtil.randomInt(ARRAY_MIN_LENGTH, ARRAY_MAX_LENGTH + 1);

        Set<Integer> set = new HashSet<>();
        while (set.size() < arrayLength) {
            set.add(RandomUtil.randomInt(0, MAX_VALUE));
        }
        int[] array = ArrayUtils.toPrimitive(set.toArray(new Integer[0]));
        Arrays.sort(array);
        return array;
    }

}
